package tech.aistar.config;

import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class LoginHandler implements Filter {

    private final String[] urlList = {
            "/user/login",
            "/user/register",
            "/bs/login.jsp",
            "/bs/register.jsp",
            "/bs/shop.jsp",
            "/bs/index.jsp",
            "/bs/single-product-group.jsp",
            "/bs/single-product-sale.jsp",
            "/bs/single-product-slider.jsp",
            "/bs/single-product-sticky-left.jsp",
            "/bs/single-product-tab-style-left.jsp",
            "/bs/single-product-tab-style-right.jsp",
            "/product/list",
            "assets",
            "about",
            "contact"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object user = request.getSession().getAttribute("userSession");
        if (user == null) {
            String requestURI = request.getRequestURI();
            boolean anyMatch = Arrays.stream(urlList).anyMatch(url -> {
                if (requestURI.contains(url)) {
                    return true;
                }
                return false;
            });
            if (anyMatch) {
                filterChain.doFilter(request, response);
                return;
            }
            // 设置响应编码
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("<script >\n" +
                    "\t\t\talert(\"未登录\")\n" +
                    "\t\t\tlocation.href=\"/bs/login.jsp\"\n" +
                    "\t\t</script>");
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
